package com.example.admin.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import com.example.admin.service.AdminService;
import com.example.xo.common.pojo.Admin;
import com.example.xo.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    public AdminService adminService;

    @PostMapping("login")
    public Result login(@RequestBody Admin admin) {
        //判断登录是否成功
        if (ObjectUtil.isEmpty(admin)) {
            return Result.error();
        }
        if (StrUtil.isBlank(admin.getEmail())) {
            return Result.error();
        }
        if (StrUtil.isBlank(admin.getPassword())) {
            return Result.error();
        }
        boolean login = adminService.login(admin);
        if (!login) {
            return Result.error();
        }
        //能走到这一步就说明邮箱和密码都对了
        //成功以后，签token
        String token = JWT.create()
                //载荷不允许放敏感信息
                //推荐必选
                .setPayload("adminId", "管理员id")
                //可选
                .setPayload("role", "管理员的角色")
                //可选
                .setPayload("name", "管理昵称")
                //key不要给出去
                .setKey("你的key".getBytes())
                .sign();
        return Result.success(token);
    }
}
